package view

import (
	"cloudops/src/common"
	"cloudops/src/config"
	"cloudops/src/models"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strconv"
	"strings"
)

func getJobExecResultByJobId(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)

	// 分页
	currentPage, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "100"))
	offset := 0
	limit := 0
	limit = pageSize
	if currentPage > 1 {
		offset = (currentPage - 1) * limit
	}

	jobIds := c.DefaultQuery("jobId", "")
	jobId, _ := strconv.Atoi(jobIds)
	objs, err := models.GetJobExecResultByJobId(jobId)
	if err != nil {
		sc.Logger.Error("根据jobid获取所有结果失败", zap.Error(err))
		common.ReqBadFailWithMessage(fmt.Sprintf("根据jobid获取所有结果失败", err.Error()), c)
		return
	}

	searchStatus := c.DefaultQuery("status", "")
	searchIp := c.DefaultQuery("ip", "")
	allIds := []int{}

	for _, obj := range objs {
		obj := obj

		if searchStatus != "" && obj.Status != searchStatus {
			continue
		}
		if searchIp != "" && !strings.Contains(obj.HostIp, searchIp) {
			continue
		}
		allIds = append(allIds, int(obj.ID))
	}

	if len(allIds) == 0 {
		common.OkWithDetailed(allIds, "ok", c)
		return
	}

	objs, err = models.GetJobResultByIdsWithLimitOffset(allIds, limit, offset)
	if err != nil {
		sc.Logger.Error("获取所有结果失败", zap.Error(err))
		common.ReqBadFailWithMessage(fmt.Sprintf("获取所有结果失败", err.Error()), c)
		return
	}

	resp := &ResponseResourceCommon{
		Total: len(allIds),
		Items: objs,
	}
	common.OkWithDetailed(resp, "ok", c)
}
